const router = require('@koa/router')()
const jwt = require('../utils/jwt.js')
const { findNoteListByType, findNoteDetailById, notePublish } = require('../controllers/index.js')
const { formateTime } = require('../utils/formateTime.js')

router.get('/findNoteListByType', jwt.verify(), async (ctx) => {
    // 检验token合理再去数据库中查找数据返回给前端
    const { note_type } = ctx.request.query
    try {
        const res = await findNoteListByType(note_type, ctx.userId)
        if (res.length) {
            ctx.body = {
                data: res,
                message: '查询成功',
                code: '800'
            }
        } else {
            ctx.body = {
                data: res,
                message: '你还没有记录笔记哦',
                code: '800'
            }
        }

    } catch (error) {
        ctx.body = {
            data: error,
            message: "查询失败",
            code: "805"
        }
    }
})

router.get('/findNoteDetailById', jwt.verify(), async (ctx) => {
    const { id } = ctx.request.query
    try {
        const res = await findNoteDetailById(id)
        if (res.length) {
            ctx.body = {
                code: "800",
                message: `我的第${id}条笔记`,
                data: res
            }
        } else {
            ctx.body = {
                code: '800',
                message: '你还没有笔记内容哦',
                data: res
            }
        }
    } catch (error) {
        ctx.body = {
            code: "805",
            message: "error",
            data: error
        }
    }
})

router.post('/note-publish', jwt.verify(), async (ctx) => {
    const { title, note_content, head_img, note_type } = ctx.request.body
    const { userId, nickname } = ctx
    const c_time = formateTime(new Date())
    const m_time = formateTime(new Date())
    try {
        const res = await notePublish({ title,note_type, note_content, head_img, c_time, m_time, nickname, userId})
        console.log(res);
        if(res.affectedRows) {
            ctx.body = {
                code: "800",
                data: res,
                message: "发布成功"
            }
        }
    } catch (error) {
        ctx.body = {
            code: "805",
            data: error,
            message: "服务器异常"
        }
    }
})

module.exports = router